import { defineStore } from "pinia"
import { ref, computed } from "vue"
import { ElMessage } from "element-plus"

// 导入API函数
import { 
  getCarriersApi, 
  getDeparturesApi, 
  getDestinationsApi, 
  searchFlightsApi,
  getFlightPriceTrendApi 
} from "../apis"
import type { PriceTrendData, ChartData, FlightSearchForm } from "@/types/flight"

interface FlightList {
  id?: string
  fno?: string
  dept?: string
  arr?: string
  depttime?: string | Date
}

interface Carrier {
  carrier: string
}

interface Location {
  dept: string
}

interface Destination {
  arr: string
}

export const useFlightStore = defineStore("flight", () => {
  // 状态
  const isLoading = ref(false)
  const flightData = ref<FlightList[]>([])
  const carriers = ref<Carrier[]>([])
  const departures = ref<Location[]>([])
  const destinations = ref<Destination[]>([])
  
  // 价格趋势相关状态
  const priceTrends = ref<Map<string, PriceTrendData[]>>(new Map()) // key: flight id, value: price trend data
  const chartData = ref<Map<string, ChartData>>(new Map()) // key: flight id, value: chart data
  const isLoadingPriceTrend = ref<Map<string, boolean>>(new Map()) // key: flight id, value: loading state
  const expandedRows = ref<Set<string>>(new Set()) // 展开的行ID集合
  
  // 分页状态
  const pagination = ref({
    current_page: 1,
    page_size: 20,
    total: 0
  })
  
  const searchCondition = ref<FlightSearchForm>({
    current_page: 1,
    page_size: 20,
    dept: '',
    arr: '',
    depttime_start: '',
    depttime_end: '',
    fno: '',
    carrier: '',
    min_price: undefined,
    max_price: undefined
  })
  
  // 缓存状态
  const cachedCarriers = ref<Carrier[]>([])
  const cachedDepartures = ref<Location[]>([])
  const cachedDestinations = ref<Destination[]>([])

  // 计算属性
  const currentPage = computed(() => pagination.value.current_page)
  const total = computed(() => pagination.value.total)
  const pageSize = computed(() => pagination.value.page_size)
  
  const getCarriersList = computed(() => 
    cachedCarriers.value.length > 0 ? cachedCarriers.value : carriers.value
  )
  
  const getDeparturesList = computed(() => 
    cachedDepartures.value.length > 0 ? cachedDepartures.value : departures.value
  )
  
  const getDestinationsList = computed(() => 
    cachedDestinations.value.length > 0 ? cachedDestinations.value : destinations.value
  )

  // 获取价格趋势数据 - 直接返回值而不是computed
  const getPriceTrendsById = (id: string) => {
    return computed(() => priceTrends.value.get(id) || [])
  }
  
  // 获取图表数据 - 直接返回值而不是computed
  const getChartDataById = (id: string) => {
    return computed(() => chartData.value.get(id))
  }
  
  // 检查行是否展开 - 直接返回值而不是computed
  const isRowExpanded = (id: string) => {
    return computed(() => expandedRows.value.has(id))
  }

  // 获取价格趋势加载状态 - 处理Map的响应式访问
  const getIsLoadingPriceTrend = (id: string) => {
    return computed(() => isLoadingPriceTrend.value.get(id) || false)
  }

  // 方法
  /** 获取航空公司列表 */
  async function fetchCarriers() {
    try {
      const response = await getCarriersApi()
      if (response.code === 0 && response.data) {
        carriers.value = response.data
        cachedCarriers.value = response.data
      } else {
        ElMessage.error(response.message || '获取航空公司列表失败')
      }
    } catch (error) {
      console.error('获取航空公司列表失败:', error)
      ElMessage.error('获取航空公司列表失败，请稍后重试')
    }
  }

  /** 获取出发地列表 */
  async function fetchDepartures() {
    try {
      const response = await getDeparturesApi()
      if (response.code === 0 && response.data) {
        departures.value = response.data
        cachedDepartures.value = response.data
      } else {
        ElMessage.error(response.message || '获取出发地列表失败')
      }
    } catch (error) {
      console.error('获取出发地列表失败:', error)
      ElMessage.error('获取出发地列表失败，请稍后重试')
    }
  }

  /** 获取目的地列表 */
  async function fetchDestinations() {
    try {
      const response = await getDestinationsApi()
      if (response.code === 0 && response.data) {
        destinations.value = response.data
        cachedDestinations.value = response.data
      } else {
        ElMessage.error(response.message || '获取目的地列表失败')
      }
    } catch (error) {
      console.error('获取目的地列表失败:', error)
      ElMessage.error('获取目的地列表失败，请稍后重试')
    }
  }

  /** 搜索航班 */
  async function fetchFlights(condition?: any) {
    try {
      isLoading.value = true
      
      // 合并查询条件
      const searchConditionData = {
        ...searchCondition.value,
        ...condition
      }
      
      searchCondition.value = { ...searchConditionData }
      
      const response = await searchFlightsApi(searchConditionData)
      
      if (response.code === 0) {
        flightData.value = response.data || []
        // 更新分页信息
        if (response.pagination) {
          pagination.value = {
            current_page: response.pagination.current_page,
            page_size: response.pagination.page_size,
            total: response.pagination.total
          }
        }
      } else {
        ElMessage.error(response.message || '搜索航班失败')
        flightData.value = []
        pagination.value = {
          current_page: 1,
          page_size: 20,
          total: 0
        }
      }
    } catch (error) {
      console.error('搜索航班失败:', error)
      ElMessage.error('搜索航班失败，请稍后重试')
      flightData.value = []
      pagination.value = {
        current_page: 1,
        page_size: 20,
        total: 0
      }
    } finally {
      isLoading.value = false
    }
  }

  /** 获取航班价格趋势数据 */
  async function fetchFlightPriceTrend(id: string) {
    try {
      // 设置加载状态
      isLoadingPriceTrend.value.set(id, true)
      
      const response = await getFlightPriceTrendApi(id)
      
      if (response.code === 0 && response.data) {
        priceTrends.value.set(id, response.data)
        
        // 处理图表数据
        const chartDataResult = processChartData(response.data)
        chartData.value.set(id, chartDataResult)
      } else {
        ElMessage.error(response.message || '获取价格趋势失败')
        priceTrends.value.set(id, [])
        chartData.value.set(id, { dates: [], prices: [], decrease_flags: [] })
      }
    } catch (error) {
      console.error('获取价格趋势失败:', error)
      ElMessage.error('获取价格趋势失败，请稍后重试')
      priceTrends.value.set(id, [])
      chartData.value.set(id, { dates: [], prices: [], decrease_flags: [] })
    } finally {
      isLoadingPriceTrend.value.set(id, false)
    }
  }

  /** 处理图表数据 */
  function processChartData(priceTrendData: PriceTrendData[]): ChartData {
    const sortedData = [...priceTrendData].sort((a, b) => {
      const dateA = new Date(a.createtime).getTime()
      const dateB = new Date(b.createtime).getTime()
      return dateA - dateB
    })
    
    return {
      dates: sortedData.map(item => {
        const date = new Date(item.createtime)
        return date.toLocaleDateString('zh-CN', {
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      }),
      prices: sortedData.map(item => item.price),
      decrease_flags: sortedData.map(item => item.decrease_flag)
    }
  }

  /** 切换行展开状态 */
  function toggleRowExpansion(id: string) {
    if (expandedRows.value.has(id)) {
      expandedRows.value.delete(id)
    } else {
      expandedRows.value.add(id)
      
      // 如果没有价格趋势数据，则获取数据
      if (!priceTrends.value.has(id)) {
        fetchFlightPriceTrend(id)
      }
    }
  }

  /** 更新搜索条件并查询 */
  function updateSearchCondition(condition: any) {
    searchCondition.value = {
      ...searchCondition.value,
      ...condition
    }
    
    // 如果更新了分页参数，也更新pagination状态
    if (condition.current_page !== undefined) {
      pagination.value.current_page = condition.current_page
    }
    if (condition.page_size !== undefined) {
      pagination.value.page_size = condition.page_size
    }
    
    // 清空展开状态和价格趋势缓存
    expandedRows.value.clear()
    priceTrends.value.clear()
    chartData.value.clear()
    
    fetchFlights()
  }

  /** 重置搜索条件 */
  function resetSearchCondition() {
    searchCondition.value = {
      current_page: 1,
      page_size: 20,
      dept: '',
      arr: '',
      depttime_start: '',
      depttime_end: '',
      fno: '',
      carrier: '',
      min_price: undefined,
      max_price: undefined
    }
    
    pagination.value = {
      current_page: 1,
      page_size: 20,
      total: 0
    }
    
    flightData.value = []
    
    // 清空价格趋势相关状态
    expandedRows.value.clear()
    priceTrends.value.clear()
    chartData.value.clear()
    isLoadingPriceTrend.value.clear()
  }

  /** 分页处理 */
  function handlePageChange(page: number) {
    updateSearchCondition({ current_page: page })
  }

  /** 页面大小变化处理 */
  function handleSizeChange(size: number) {
    updateSearchCondition({ 
      page_size: size,
      current_page: 1 
    })
  }

  /** 初始化选项数据 */
  async function initializeOptions() {
    await Promise.all([
      fetchCarriers(),
      fetchDepartures(),
      fetchDestinations()
    ])
  }

  return {
    // 状态
    isLoading,
    flightData,
    carriers,
    departures,
    destinations,
    priceTrends,
    chartData,
    isLoadingPriceTrend,
    expandedRows,
    pagination,
    searchCondition,
    cachedCarriers,
    cachedDepartures,
    cachedDestinations,
    
    // 计算属性
    currentPage,
    total,
    pageSize,
    getCarriersList,
    getDeparturesList,
    getDestinationsList,
    getPriceTrendsById,
    getChartDataById,
    isRowExpanded,
    getIsLoadingPriceTrend,
    
    // 方法
    fetchCarriers,
    fetchDepartures,
    fetchDestinations,
    fetchFlights,
    fetchFlightPriceTrend,
    toggleRowExpansion,
    updateSearchCondition,
    resetSearchCondition,
    handlePageChange,
    handleSizeChange,
    initializeOptions
  }
})
